var http = require('http');
// Array of type JSON. The content have to be persisted in SAP database.
var arrayJSON = new Array();
var arrayProcess = new Array();





// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  
  if ( request.method === 'POST' ) {

     // the body of the POST is JSON payload.
     var data = '';
     request.on('data', function(chunk) {
                          data += chunk;
                                     });

     request.on('end', function() {
                                                           try 
                                                           {
	                                                              data = JSON.parse(data);
	                                                              if 	  (data.header.cmd === "R"){// Registration
	                                                                   			saveTimeReg(data, response);
			                                                      }
			                                                      else if (data.header.cmd === "L"){// Login
			                                                                   	requestLogin(response, data);
			                                                      }
			                                                      else if (data.header.cmd === "TA"){// Login
	                                                                   			requestLoginData(response, data);
			                                                      }
			                                                      else if (data.header.cmd === "S"){// SAP calls with "cmd" value "S". Receive JSON with all TimeRegistrations. Resets the JSONArray.
			                                                   	   		requestNewProcess();
			                                                    	  //sendDataSAP(response);
			                                                      }
			                                                      else{
			                                                   	   response.end;
			                                                      }
                                                           } 
                                                           catch (e) 
                                                           {
                                                               console.log(e);
                                                       			var exceptionJSON = {status:2} //No connection to backend.
                                                       			writeResponse(response, exceptionJSON);
                                                           } 
                                                           

                                                     }
     );
  }
});

function sendDataSAP(response){
	
    writeResponse(response, JSON.parse(arrayProcess));
}
function saveTimeReg(content, response){
    arrayJSON.push(content);
    
    var output = "TimeRegistration(";
    output += "UserID: "+content.id;
    output += ", WBS:"+content.wbs;
    output += ", Date:"+content.date;
    output += ", Hours:"+content.time;
    output += ")"
    console.log(output);
    
    var objToJson = {"id":content.id, "status": 200}; 
    writeResponse(response, objToJson);
    
}

function read(response, id){
	var http2 = require('http');
	var user = {userID: id};
	var responseString = ""; 
	var userString = JSON.stringify(user);
	 
	var headers = {
	   'Content-Type': 'application/json',
	   'Content-Length': userString.length
	 };
	 
	// Setup the request.  The options parameter is
	 // the object we defined above.
	 var req = http2.request(options, function(res) {
		   	res.setEncoding('utf-8');
		 
		   	res.on('data', function(data) {
		   		responseString += data;
		   	});
		 
		   	res.on('end', function() {
		   		var jsonFromSAP = JSON.parse(responseString);
		   		writeResponse(response, jsonFromSAP);

		   	});
	 });
	 
	req.on('error', function(e) {
		var exceptionJSON = {status:2} //No connection to backend.
		writeResponse(response, exceptionJSON);
	 });
	 
	req.write(userString);
	 
	req.end();

}

function writeResponse(response, jsonObj){
    response.writeHeader(200, {"Content-Type": "Application/json"});
    response.write(JSON.stringify(jsonObj));
    response.end();
}

function requestLogin(response, content){
	// This method should, save the request for the UserData in a array.
	// The information we save in this array will later on be fetched and processed by SAP.	
	arrayProcess.push("requestUser " + content.id);
  //  var output = arrayProcess.
    console.log(arrayProcess);	
    var status = "200";
    jsonString += "{\"id\":\""+content.id + "\", \"status\":\""+status+"\"}";
    // Make a method that can return at "OK-received" kind of message to the device
    writeResponse(response, JSON.parse(jsonString));
	
}
function requestLoginData(response, content){

    writeResponse(response, JSON.parse(jsonString));
	
}

function requestNewProcess(){
	// This method should, save the request for the UserData in a array.
	// The information we save in this array will later on be fetched and processed by SAP.	
	
	console.log(arrayProcess.shift());	
	
    
    // Make a method that can return at "OK-received" kind of message to the device
	return response;
}





// Listen on port 8000, IP default
server.listen(8000);

console.log("Server running...");



